package com.metering.purchaseServerAdmin.controller;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.metering.purchaseServerAdmin.domain.UserDO;
import com.metering.purchaseServerAdmin.dto.LoginDTO;
import com.metering.purchaseServerAdmin.service.MenuService;
import com.metering.purchaseServerAdmin.service.TokenService;
import com.metering.purchaseServerAdmin.service.UserService;
import com.metering.purchaseServerAdmin.utils.MD5Utils;
import com.metering.purchaseServerCommon.common.bean.annotation.Log;
import com.metering.purchaseServerCommon.common.bean.dto.UserToken;
import com.metering.purchaseServerCommon.common.bean.util.JwtUtils;
import com.metering.purchaseServerCommon.common.bean.util.R;

/**
 * 
 * @ClassName: LoginController
 * @Description:
 * @Author GA
 * @DateTime 2018年12月20日 上午10:20:42
 */

@RestController
@RequestMapping()
public class LoginController extends BaseController {

	@Autowired
	private UserService userService;

	@Autowired
	private TokenService tokenService;

	@Autowired
	private MenuService menuService;

	@Log("登录")
	@PostMapping("/login")
	public R login(@Valid @RequestBody LoginDTO loginDTO, HttpServletRequest request, HttpServletResponse response) {
		String username = loginDTO.getUsername().trim();
		String password = loginDTO.getPwd().trim();
		password = MD5Utils.encrypt(username, password);
		Map<String, Object> param = new HashMap<>();
		param.put("username", username);
		List<UserDO> userDOs = userService.list(param);
		if (userDOs.size() < 1) {
			return R.error("用户或密码错误");
		}
		UserDO userDO = userDOs.get(0);
		if (null == userDO || !userDO.getPassword().equals(password)) {
			return R.error("用户或密码错误");
		}
		UserToken userToken = new UserToken(userDO.getUsername(), userDO.getUserId().toString(), userDO.getName());
		String token = "";
		try {
			token = JwtUtils.generateToken(userToken, 2 * 60 * 60 * 1000);
		} catch (Exception e) {
			e.printStackTrace();
		}
		// 首先清除用户缓存权限
		menuService.clearCache(userDO.getUserId());
		// String token = tokenService.createToken(userDO.getUserId());
		return R.ok("登录成功").put("token", token).put("user", userDO)
				.put("perms", menuService.PermsByUserId(userDO.getUserId()))
				.put("router", menuService.RouterDTOsByUserId(userDO.getUserId()));
	}
}
